//
//  STLanguageController.swift
//  iPhone
//
//  Created by Toj on 4/20/23.
//

import UIKit

// MARK: - 懒加载(属性), 变量, 初始化init
class STLanguageController: STBaseViewController {
    
    private lazy var tableView: UITableView = {
        let view = UITableView()
        view.backgroundColor = .white
        view.rowHeight = 44
        view.dataSource = self
        view.delegate = self
        view.register(cellClass: UITableViewCell.self)
        return view
    }()
    
    private var localizations = [String]() { didSet {
        tableView.reloadData()
    } }
    private var currentLanguage = ""
}

// MARK: - 生命周期
extension STLanguageController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupMakeInitialize()
        setupMakeAddSubviews()
        setupMakeLayoutSubviews()
    }
}

extension STLanguageController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return localizations.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withReuseIdentifierClass: UITableViewCell.self)
        // print("-->toj: address:" + cell.cm_objectAddress + ", num:" + String(indexPath.row))
        cell.textLabel?.text = localizations[indexPath.row]
      
        return cell
    }
}

extension STLanguageController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let localized = tableView.cellForItem(at: indexPath, convertTo: UITableViewCell.self)?.textLabel?.text else { return }
        
        CMLocalized.defalut.setLanguage(localized)
        print("-->toj: current:\(CMLocalized.defalut.current)")
    }
}

// MARK: - 初始化设置
private extension STLanguageController {
    
    func setupMakeAddSubviews() {
        view.addSubview(tableView)
    }
    
    func setupMakeLayoutSubviews() {
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(view)
            make.top.equalTo(CGFloat.nav_barFullHeight)
        }
    }
    
    func setupMakeInitialize() {
        view.backgroundColor = .white
        currentLanguage = CMLocalized.defalut.current
        
        // app支持的语言
        localizations = CMLocalized.defalut.localizations
    }
}
